package com.sinochem.sales.gateway.componet.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sinochem.sales.admin.api.to.UserTO;
import com.sinochem.sales.common.constant.SecurityConstants;
import com.sinochem.sales.common.util.UserUtils;
import org.sagacity.sqltoy.utils.CollectionUtil;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.Map;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/3 13:34
 * @project parent
 * @description 在RateLimitPreFilter 之前执行，不然又空指针问题
 * @Modification Date: 2018/4/3 13:34  {填写修改说明}
 */
@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * https://docs.spring.io/spring-security/site/docs/5.0.4.RELEASE/reference/htmlsingle/
     *
     * @return
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();

        ctx.set("startTime", System.currentTimeMillis());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal.equals("anonymousUser")) {
            return null;
        }
        RequestContext requestContext = setUID(authentication);
        if (principal instanceof UserDetails) {
            requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, ((UserDetails) principal).getUsername());
        } else {
            requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
        }

        return null;
    }

    private RequestContext setUID(Authentication authentication) {
        OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
        String tokenValue = oAuth2AuthenticationDetails.getTokenValue();
        Map<String, Object> userIdByToken = UserUtils.getUserIdByToken(tokenValue);
        Object userId = userIdByToken.get("userId");
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.addZuulRequestHeader(SecurityConstants.UID_HEADER, userId.toString());
        return requestContext;
    }
}
